# -*- coding: utf-8 -*-

'''
信息管理函数
'''
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
import pandas as pd
import uuid
import datetime
import re
import hashlib
from enum import Enum
from ...service.mongo_bill_service import MongoBillFilter
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ..buss_pub.personnel_organizational import UserType
from server.pao_python.pao.data import process_db
from ...service.common import get_current_user_id


class MessageState(Enum):
    '''信息状态
    '''
    Already_read = '已读'
    Unread = '未读'


class MessageManageService(MongoService):
    ''' 信息管理 '''
    Message = 'PT_Message'
    Message_type = 'PT_Message_Type'

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def get_all_message_list(self, condition, page, count):
        '''获取信息列表
        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        keys = ['id', 'name', 'message_state', 'receive_info']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('message_state') == values['message_state'])
                           & (C('receive_info') == values['receive_info'])
                           & (C('name').like(values['name'])))\
            .unwind('receive_info', True)\
            .lookup_bill(self.Message_type, 'message_type', 'id', 'message_type_info')\
            .unwind('message_type_info', True)\
            .lookup_bill('PT_User', 'message_creator', 'id', 'message_creator_info')\
            .unwind('message_creator_info', True)\
            .add_fields({'message_type_name': '$message_type_info.name', 'message_creator': '$message_creator_info.name'})\
            .project({'_id': 0, 'message_type_info': 0, 'message_creator_info': 0})
        res = self.page_query(_filter, self.Message, page, count)
        return res

    def get_unread_message_list(self, condition, page, count):
        '''获取未读的信息列表'''
        condition['message_state'] = MessageState.Unread.value
        condition['receive_info'] = get_current_user_id(self.session)
        return self.get_all_message_list(condition, page, count)

    def set_message_already_read(self, message):
        res = 'Fail'

        if 'id' in message.keys():
            message['message_state'] = MessageState.Already_read.value
        bill_id = self.bill_manage_server.add_bill(
            OperationType.update.value, TypeId.message.value, message, self.Message)
        if bill_id:
            res = 'Success'
        return res

    def add_new_message(self, data):
        # 创建一个未读信息
        res = 'Fail'
        # 未读状态
        data['message_state'] = MessageState.Unread.value  # 增加状态，待处理
        # 创建信息的人
        data['message_creator'] = get_current_user_id(self.session)

        # 信息推送时间处理
        if 'push_date' in data.keys():
            data['push_date'] = as_date(data['push_date'])

        # 接受信息的人
        if 'receive_info' not in data.keys():
            data['receive_info'] = []
        else:
            data['receive_info'] = [data['receive_info']]

        bill_id = self.bill_manage_server.add_bill(
            OperationType.add.value, TypeId.message.value, data, self.Message)
        if bill_id:
            res = 'Success'
        return res

    def get_message_type_list(self, condition, page, count):
        '''获取信息类型列表
        Arguments:
            condition   {dict}      条件
            page        {number}    页码
            count       {number}    条数
        '''
        keys = ['id', 'name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('id') == values['id'])
                           & (C('name').like(values['name'])))\
            .project({'_id': 0})
        res = self.page_query(_filter, self.Message_type, page, count)
        return res

    def add_new_message_type(self, data):
        # 创建一个信息类型
        res = 'Fail'

        # 检测是否有创建过
        keys = ['id', 'name']
        values = self.get_value({}, keys)
        _filter = MongoBillFilter()
        _filter.match_bill((C('name').like(values['name'])))\
            .project({'_id': 0})
        res = self.query(_filter, self.Message_type)

        if(len(res) > 0):
            return 'exists'

        # 创建信息类型时间
        data['create_date'] = datetime.datetime.now()
        # 备注
        data['remark'] = '测试类型'
        bill_id = self.bill_manage_server.add_bill(
            OperationType.add.value, TypeId.task.value, data, self.Message_type)
        if bill_id:
            res = 'Success'
        return res
